<template>
  <div class="approvals">
    <div class="page-container">
      <div class="page-header">
        <h2>待我审批</h2>
        <div class="header-actions">
          <el-badge :value="urgentCount" :hidden="urgentCount === 0" class="urgent-badge">
            <el-button type="warning" @click="showUrgentOnly">
              <el-icon><Warning /></el-icon>
              紧急审批
            </el-button>
          </el-badge>
          <el-button @click="refreshList">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
      
      <!-- 筛选条件 -->
      <el-card class="filter-card">
        <el-form :model="searchForm" inline>
          <el-form-item label="紧急程度">
            <el-select v-model="searchForm.priority" placeholder="全部" clearable>
              <el-option label="全部" value="" />
              <el-option label="紧急" value="urgent" />
              <el-option label="普通" value="normal" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="作业类型">
            <el-select v-model="searchForm.workType" placeholder="全部类型" clearable>
              <el-option label="全部" value="" />
              <el-option label="高空作业" value="high_altitude" />
              <el-option label="动火作业" value="hot_work" />
              <el-option label="电气作业" value="electrical" />
              <el-option label="受限空间" value="confined_space" />
              <el-option label="起重作业" value="lifting" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="申请时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
      
      <!-- 审批列表 -->
      <el-card>
        <el-table
          v-loading="loading"
          :data="tableData"
          stripe
          border
          @row-click="handleRowClick"
        >
          <el-table-column prop="permitNumber" label="许可证编号" width="150">
            <template #default="{ row }">
              <div class="permit-number">
                <span>{{ row.permitNumber }}</span>
                <el-tag v-if="row.priority === 'urgent'" type="danger" size="small" style="margin-left: 8px">
                  紧急
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="workType" label="作业类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getWorkTypeTagType(row.workType)">
                {{ getWorkTypeLabel(row.workType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="location" label="作业地点" width="200" />
          <el-table-column prop="applicant" label="申请人" width="100" />
          <el-table-column prop="department" label="申请部门" width="120" />
          <el-table-column prop="startTime" label="计划开始时间" width="160" />
          <el-table-column prop="endTime" label="计划结束时间" width="160" />
          <el-table-column prop="submitTime" label="提交时间" width="160" />
          <el-table-column prop="approvalStep" label="审批步骤" width="120">
            <template #default="{ row }">
              <el-tag type="warning" size="small">
                {{ row.approvalStep }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click.stop="handleApprove(row)">
                审批
              </el-button>
              <el-button type="info" size="small" @click.stop="handleView(row)">
                查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
    
    <!-- 审批对话框 -->
    <ApprovalDialog
      v-model="approvalDialogVisible"
      :approval-data="currentApproval"
      @success="handleApprovalSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import ApprovalDialog from './components/ApprovalDialog.vue'

const router = useRouter()

interface ApprovalItem {
  id: number
  permitNumber: string
  workType: string
  location: string
  applicant: string
  department: string
  startTime: string
  endTime: string
  submitTime: string
  approvalStep: string
  priority: 'urgent' | 'normal'
  workContent: string
  safetyMeasures: string[]
  personnel: any[]
  gasDetectors: any[]
}

const loading = ref(false)
const tableData = ref<ApprovalItem[]>([])
const approvalDialogVisible = ref(false)
const currentApproval = ref<ApprovalItem | null>(null)

const searchForm = reactive({
  priority: '',
  workType: '',
  dateRange: []
})

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 紧急审批数量
const urgentCount = computed(() => {
  return tableData.value.filter(item => item.priority === 'urgent').length
})

// 模拟数据
const mockData: ApprovalItem[] = [
  {
    id: 1,
    permitNumber: 'WP20250115001',
    workType: 'high_altitude',
    location: 'A区3楼外墙维修',
    applicant: '张三',
    department: '维修部',
    startTime: '2025-01-16 08:00',
    endTime: '2025-01-16 17:00',
    submitTime: '2025-01-15 14:30',
    approvalStep: '班长审批',
    priority: 'urgent',
    workContent: '外墙保温层维修，需要高空作业',
    safetyMeasures: ['佩戴安全帽', '系安全带', '配备灭火器'],
    personnel: [
      { name: '李四', type: '高空作业', certificateExpiry: '2025-12-31' }
    ],
    gasDetectors: [
      { name: '王五', role: '气测员', department: '安全部' }
    ]
  },
  {
    id: 2,
    permitNumber: 'WP20250115002',
    workType: 'hot_work',
    location: 'B区管道焊接',
    applicant: '赵六',
    department: '维修部',
    startTime: '2025-01-17 09:00',
    endTime: '2025-01-17 15:00',
    submitTime: '2025-01-15 10:20',
    approvalStep: '安全员审批',
    priority: 'normal',
    workContent: '管道焊接作业，需要动火',
    safetyMeasures: ['配备灭火器', '气体检测', '隔离措施'],
    personnel: [
      { name: '钱七', type: '焊工', certificateExpiry: '2025-10-15' }
    ],
    gasDetectors: [
      { name: '孙八', role: '气测员', department: '安全部' }
    ]
  },
  {
    id: 3,
    permitNumber: 'WP20250115003',
    workType: 'electrical',
    location: '配电室设备检修',
    applicant: '周九',
    department: '维修部',
    startTime: '2025-01-18 08:30',
    endTime: '2025-01-18 16:30',
    submitTime: '2025-01-15 09:15',
    approvalStep: '部门经理审批',
    priority: 'normal',
    workContent: '配电室设备检修，需要停电作业',
    safetyMeasures: ['隔离措施', '气体检测', '佩戴安全帽'],
    personnel: [
      { name: '吴十', type: '电工', certificateExpiry: '2025-11-30' }
    ],
    gasDetectors: [
      { name: '郑十一', role: '安全员', department: '安全部' }
    ]
  }
]

// 获取审批列表
const fetchApprovals = async () => {
  try {
    loading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    let filteredData = mockData
    
    // 根据筛选条件过滤
    if (searchForm.priority) {
      filteredData = filteredData.filter(item => item.priority === searchForm.priority)
    }
    
    if (searchForm.workType) {
      filteredData = filteredData.filter(item => item.workType === searchForm.workType)
    }
    
    // 分页
    const start = (pagination.page - 1) * pagination.size
    const end = start + pagination.size
    
    tableData.value = filteredData.slice(start, end)
    pagination.total = filteredData.length
  } catch (error: any) {
    ElMessage.error(error.message || '获取审批列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchApprovals()
}

// 重置
const handleReset = () => {
  searchForm.priority = ''
  searchForm.workType = ''
  searchForm.dateRange = []
  pagination.page = 1
  fetchApprovals()
}

// 显示紧急审批
const showUrgentOnly = () => {
  searchForm.priority = 'urgent'
  handleSearch()
}

// 刷新列表
const refreshList = () => {
  fetchApprovals()
  ElMessage.success('刷新成功')
}

// 行点击
const handleRowClick = (row: ApprovalItem) => {
  handleView(row)
}

// 查看详情
const handleView = (row: ApprovalItem) => {
  router.push(`/permit/detail/${row.id}`)
}

// 审批
const handleApprove = (row: ApprovalItem) => {
  currentApproval.value = row
  approvalDialogVisible.value = true
}

// 审批成功
const handleApprovalSuccess = () => {
  fetchApprovals()
  ElMessage.success('审批完成')
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  fetchApprovals()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchApprovals()
}

// 获取作业类型标签类型
const getWorkTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    high_altitude: 'warning',
    hot_work: 'danger',
    electrical: 'primary',
    confined_space: 'info',
    lifting: 'success'
  }
  return typeMap[type] || 'info'
}

// 获取作业类型标签
const getWorkTypeLabel = (type: string) => {
  const labelMap: Record<string, string> = {
    high_altitude: '高空作业',
    hot_work: '动火作业',
    electrical: '电气作业',
    confined_space: '受限空间',
    lifting: '起重作业'
  }
  return labelMap[type] || type
}

onMounted(() => {
  fetchApprovals()
})
</script>

<style lang="scss" scoped>
.approvals {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #333;
    }
    
    .header-actions {
      display: flex;
      gap: 12px;
      align-items: center;
      
      .urgent-badge {
        .el-button {
          border-color: #e6a23c;
          color: #e6a23c;
        }
      }
    }
  }
  
  .filter-card {
    margin-bottom: 20px;
  }
  
  .permit-number {
    display: flex;
    align-items: center;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
